package com.fifth.apartment.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fifth.apartment.entity.Menu;
import com.fifth.apartment.entity.Permission;
import com.fifth.apartment.entity.Role;
import com.fifth.apartment.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    public LoginUser (User user){
        this.user = user;
    }

    //存储到redis中
    private List<SimpleGrantedAuthority> authorities;

    //把权限信息封装成SimpleGrantedAuthority对象
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (!CollectionUtils.isEmpty(authorities)){
            return authorities;
        }
        authorities = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        roles.stream().forEach(role -> {
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            Set<Menu> menus = role.getMenus();
            permissions.stream().forEach(permission -> {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            });
            menus.stream().forEach(menu -> {
                authorities.add(new SimpleGrantedAuthority(menu.getTitle()));
            });
        });
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getState().equals("1")?true:false;
    }
}
